package com.ruoyi.project.system.controller;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.CheckoutUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.TencentApi;
import com.ruoyi.framework.aspectj.lang.annotation.Anonymous;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.mapper.SysUserMapper;
import com.ruoyi.project.system.service.ISysUserService;
import com.ruoyi.project.system.service.TencentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

@RestController
@RequestMapping("/wx")
public class WeiController {

    @Autowired
    private ISysUserService iSysUserService;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private TencentService tencentService;

    @Anonymous
    @GetMapping("/QRCodeImg")
    public JSONObject QRCodeImg() {
         return tencentService.getTemporaryOfficialAccountsQRCode(SecurityUtils.getUserId());
    }

    @Anonymous
    @RequestMapping("/weChatToken")
    public void weChat(HttpServletRequest request, HttpServletResponse response) {
        boolean isGet = request.getMethod().equalsIgnoreCase("get");
        if (isGet) {
            // 微信加密签名
            String signature = request.getParameter("signature");
            // 时间戳
            String timestamp = request.getParameter("timestamp");
            // 随机数
            String nonce = request.getParameter("nonce");
            // 随机字符串
            String echostr = request.getParameter("echostr");
            // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
            if (signature != null && CheckoutUtil.checkSignature(signature, timestamp, nonce)) {
                try {
                    PrintWriter print = response.getWriter();
                    print.write(echostr);
                    print.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }else {
            try {
                Map<String, String> map = TencentApi.notifyDecode(request);
                String event = map.get("Event");
                if ("subscribe".equals(event)){
                    String userId = map.get("EventKey").substring(8);
                    String openId = map.get("FromUserName");
                    iSysUserService.updateUser(new SysUser(Long.parseLong(userId)).setOpenId(openId));
                }else if("unsubscribe".equals(event)){
                    String openId = map.get("FromUserName");
                    sysUserMapper.clearOpenId(openId);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
